package com.ivi.car.module.city.view.adapter;

import android.view.View;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.ivi.car.R;
import com.ivi.car.module.city.model.SortModel;

import java.util.List;

/**
 * 选择城市列表的adapter
 */

public class CityListAdapter extends BaseQuickAdapter<SortModel, BaseViewHolder> {
    private List<SortModel> list;
    private final  int noPosition = -1;
    public CityListAdapter(int layoutResId, List<SortModel> data) {
        super(layoutResId, data);
        this.list = data;
    }

    @Override
    protected void convert(BaseViewHolder helper, SortModel item) {
        int position = helper.getLayoutPosition() - 1;
        int section = getSectionForPosition(position);
        TextView citySort = helper.getView(R.id.city_sort);
        if (position == getPositionForSection(section)) {
            citySort.setVisibility(View.VISIBLE);
            helper.setText(R.id.city_sort, item.getSortLetters());
        } else {
            citySort.setVisibility(View.GONE);
        }
        helper.setText(R.id.city_name, item.getName());
    }

    /**
     * @param position 当前位置
     * @return 根据的当前位置获取分类的首字母的值
     */
    private int getSectionForPosition(int position) {
        return list.get(position).getSortLetters().charAt(0);
    }

    /**
     * @param section 首字母出现的位置
     * @return 根据分类的首字母的值获取其第一次出现该首字母的位置
     */
    public int getPositionForSection(int section) {
        for (int i = 0; i < getItemCount() - 1; i++) {
            String sortLetters = list.get(i).getSortLetters();
            char c = sortLetters.toUpperCase().charAt(0);
            if (c == section) {
                return i;
            }
        }
        return noPosition;
    }
}
